import React, { useState, useRef } from "react";
import { 
  StyleSheet, 
  Text, 
  View, 
  TextInput,
  TouchableOpacity,
  ScrollView,
  KeyboardAvoidingView,
  Platform
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { 
  Send, 
  Sparkles, 
  Volume2, 
  Copy, 
  MoreHorizontal,
  ChevronDown
} from "lucide-react-native";
import { colors } from "@/constants/colors";
import { Button } from "@/components/Button";
import { useAIStore } from "@/store/ai-store";

export default function AIChatScreen() {
  const scrollViewRef = useRef<ScrollView>(null);
  const { dialogues, currentDialogue, isGenerating, generateDialogue } = useAIStore();
  const [keywords, setKeywords] = useState("");
  const [difficulty, setDifficulty] = useState<"beginner" | "intermediate" | "advanced">("beginner");
  const [showDifficultySelector, setShowDifficultySelector] = useState(false);
  
  const handleGenerate = async () => {
    if (!keywords.trim()) return;
    
    const keywordArray = keywords
      .split(",")
      .map(k => k.trim())
      .filter(k => k.length > 0);
    
    if (keywordArray.length === 0) return;
    
    await generateDialogue(keywordArray, difficulty);
    setKeywords("");
    
    // Scroll to bottom after dialogue is generated
    setTimeout(() => {
      scrollViewRef.current?.scrollToEnd({ animated: true });
    }, 100);
  };
  
  const toggleDifficultySelector = () => {
    setShowDifficultySelector(!showDifficultySelector);
  };
  
  const selectDifficulty = (selected: "beginner" | "intermediate" | "advanced") => {
    setDifficulty(selected);
    setShowDifficultySelector(false);
  };
  
  const getDifficultyColor = (level: string) => {
    switch (level) {
      case "beginner":
        return colors.success;
      case "intermediate":
        return colors.secondary;
      case "advanced":
        return colors.accent;
      default:
        return colors.primary;
    }
  };
  
  const formatDialogue = (text: string) => {
    return text.split("\n").map((line, index) => (
      <Text key={index} style={styles.dialogueText}>
        {line}
      </Text>
    ));
  };
  
  return (
    <SafeAreaView style={styles.container} edges={["top"]}>
      <KeyboardAvoidingView 
        style={styles.keyboardAvoidingView}
        behavior={Platform.OS === "ios" ? "padding" : undefined}
        keyboardVerticalOffset={Platform.OS === "ios" ? 90 : 0}
      >
        <View style={styles.header}>
          <Text style={styles.title}>AI English Dialogue</Text>
          <Text style={styles.subtitle}>
            Enter keywords to generate a conversation
          </Text>
        </View>
        
        <ScrollView
          ref={scrollViewRef}
          style={styles.scrollView}
          contentContainerStyle={styles.scrollContent}
        >
          {/* Instructions */}
          <View style={styles.instructionsCard}>
            <View style={styles.instructionsHeader}>
              <Sparkles size={20} color={colors.primary} />
              <Text style={styles.instructionsTitle}>How to use</Text>
            </View>
            <Text style={styles.instructionsText}>
              1. Enter keywords separated by commas (e.g., "cat, dog, park")
            </Text>
            <Text style={styles.instructionsText}>
              2. Select difficulty level
            </Text>
            <Text style={styles.instructionsText}>
              3. Tap "Generate Dialogue" to create a conversation
            </Text>
          </View>
          
          {/* Current dialogue */}
          {currentDialogue && (
            <View style={styles.dialogueCard}>
              <View style={styles.dialogueHeader}>
                <View>
                  <Text style={styles.dialogueTitle}>English Dialogue</Text>
                  <View style={styles.keywordsContainer}>
                    {currentDialogue.keywords.map((keyword, index) => (
                      <View key={index} style={styles.keywordChip}>
                        <Text style={styles.keywordText}>{keyword}</Text>
                      </View>
                    ))}
                  </View>
                </View>
                <View 
                  style={[
                    styles.difficultyBadge,
                    { backgroundColor: getDifficultyColor(currentDialogue.difficulty) + "20" }
                  ]}
                >
                  <Text 
                    style={[
                      styles.difficultyText,
                      { color: getDifficultyColor(currentDialogue.difficulty) }
                    ]}
                  >
                    {currentDialogue.difficulty}
                  </Text>
                </View>
              </View>
              
              <View style={styles.dialogueContent}>
                {formatDialogue(currentDialogue.english)}
              </View>
              
              <View style={styles.dialogueActions}>
                <TouchableOpacity style={styles.actionButton}>
                  <Volume2 size={20} color={colors.primary} />
                </TouchableOpacity>
                <TouchableOpacity style={styles.actionButton}>
                  <Copy size={20} color={colors.primary} />
                </TouchableOpacity>
                <TouchableOpacity style={styles.actionButton}>
                  <MoreHorizontal size={20} color={colors.primary} />
                </TouchableOpacity>
              </View>
              
              <View style={styles.translationContainer}>
                <Text style={styles.translationTitle}>Chinese Translation</Text>
                <View style={styles.translationContent}>
                  {formatDialogue(currentDialogue.chinese)}
                </View>
              </View>
            </View>
          )}
          
          {/* Previous dialogues */}
          {dialogues.length > 1 && currentDialogue && (
            <View style={styles.previousDialoguesContainer}>
              <Text style={styles.previousDialoguesTitle}>Previous Dialogues</Text>
              {dialogues
                .filter(dialogue => dialogue.id !== currentDialogue.id)
                .slice(0, 3)
                .map(dialogue => (
                  <View key={dialogue.id} style={styles.previousDialogueCard}>
                    <View style={styles.previousDialogueHeader}>
                      <View style={styles.keywordsContainer}>
                        {dialogue.keywords.map((keyword, index) => (
                          <View key={index} style={styles.keywordChip}>
                            <Text style={styles.keywordText}>{keyword}</Text>
                          </View>
                        ))}
                      </View>
                      <View 
                        style={[
                          styles.difficultyBadge,
                          { backgroundColor: getDifficultyColor(dialogue.difficulty) + "20" }
                        ]}
                      >
                        <Text 
                          style={[
                            styles.difficultyText,
                            { color: getDifficultyColor(dialogue.difficulty) }
                          ]}
                        >
                          {dialogue.difficulty}
                        </Text>
                      </View>
                    </View>
                    <Text style={styles.previousDialogueText} numberOfLines={2}>
                      {dialogue.english.substring(0, 100)}...
                    </Text>
                  </View>
                ))}
            </View>
          )}
        </ScrollView>
        
        <View style={styles.inputContainer}>
          <View style={styles.difficultyContainer}>
            <TouchableOpacity 
              style={styles.difficultySelector}
              onPress={toggleDifficultySelector}
            >
              <View 
                style={[
                  styles.difficultyBadge,
                  { backgroundColor: getDifficultyColor(difficulty) + "20" }
                ]}
              >
                <Text 
                  style={[
                    styles.difficultyText,
                    { color: getDifficultyColor(difficulty) }
                  ]}
                >
                  {difficulty}
                </Text>
              </View>
              <ChevronDown size={16} color={colors.text.secondary} />
            </TouchableOpacity>
            
            {showDifficultySelector && (
              <View style={styles.difficultyDropdown}>
                <TouchableOpacity
                  style={styles.difficultyOption}
                  onPress={() => selectDifficulty("beginner")}
                >
                  <Text 
                    style={[
                      styles.difficultyOptionText,
                      { color: getDifficultyColor("beginner") }
                    ]}
                  >
                    beginner
                  </Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.difficultyOption}
                  onPress={() => selectDifficulty("intermediate")}
                >
                  <Text 
                    style={[
                      styles.difficultyOptionText,
                      { color: getDifficultyColor("intermediate") }
                    ]}
                  >
                    intermediate
                  </Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.difficultyOption}
                  onPress={() => selectDifficulty("advanced")}
                >
                  <Text 
                    style={[
                      styles.difficultyOptionText,
                      { color: getDifficultyColor("advanced") }
                    ]}
                  >
                    advanced
                  </Text>
                </TouchableOpacity>
              </View>
            )}
          </View>
          
          <View style={styles.inputRow}>
            <TextInput
              style={styles.input}
              placeholder="Enter keywords separated by commas..."
              value={keywords}
              onChangeText={setKeywords}
              multiline
            />
            <Button
              title="Generate"
              onPress={handleGenerate}
              isLoading={isGenerating}
              disabled={!keywords.trim() || isGenerating}
              size="small"
              style={styles.generateButton}
              leftIcon={<Sparkles size={16} color={colors.text.inverse} />}
            />
          </View>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  header: {
    padding: 16,
    paddingBottom: 8,
  },
  title: {
    fontSize: 24,
    fontWeight: "700",
    color: colors.text.primary,
    marginBottom: 4,
  },
  subtitle: {
    fontSize: 16,
    color: colors.text.secondary,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    padding: 16,
    paddingBottom: 24,
  },
  instructionsCard: {
    backgroundColor: colors.card,
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
  },
  instructionsHeader: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 12,
  },
  instructionsTitle: {
    fontSize: 16,
    fontWeight: "600",
    color: colors.text.primary,
    marginLeft: 8,
  },
  instructionsText: {
    fontSize: 14,
    color: colors.text.secondary,
    marginBottom: 8,
  },
  dialogueCard: {
    backgroundColor: colors.background,
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
    borderWidth: 1,
    borderColor: colors.border,
  },
  dialogueHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-start",
    marginBottom: 12,
  },
  dialogueTitle: {
    fontSize: 16,
    fontWeight: "600",
    color: colors.text.primary,
    marginBottom: 8,
  },
  keywordsContainer: {
    flexDirection: "row",
    flexWrap: "wrap",
  },
  keywordChip: {
    backgroundColor: colors.primary + "20",
    borderRadius: 12,
    paddingHorizontal: 8,
    paddingVertical: 4,
    marginRight: 8,
    marginBottom: 8,
  },
  keywordText: {
    fontSize: 12,
    color: colors.primary,
  },
  difficultyBadge: {
    borderRadius: 12,
    paddingHorizontal: 8,
    paddingVertical: 4,
  },
  difficultyText: {
    fontSize: 12,
    fontWeight: "500",
  },
  dialogueContent: {
    marginBottom: 16,
  },
  dialogueText: {
    fontSize: 16,
    color: colors.text.primary,
    marginBottom: 8,
    lineHeight: 24,
  },
  dialogueActions: {
    flexDirection: "row",
    marginBottom: 16,
  },
  actionButton: {
    padding: 8,
    marginRight: 16,
  },
  translationContainer: {
    borderTopWidth: 1,
    borderTopColor: colors.border,
    paddingTop: 16,
  },
  translationTitle: {
    fontSize: 14,
    fontWeight: "600",
    color: colors.text.secondary,
    marginBottom: 8,
  },
  translationContent: {
    
  },
  previousDialoguesContainer: {
    marginTop: 8,
  },
  previousDialoguesTitle: {
    fontSize: 16,
    fontWeight: "600",
    color: colors.text.primary,
    marginBottom: 12,
  },
  previousDialogueCard: {
    backgroundColor: colors.card,
    borderRadius: 12,
    padding: 12,
    marginBottom: 12,
  },
  previousDialogueHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-start",
    marginBottom: 8,
  },
  previousDialogueText: {
    fontSize: 14,
    color: colors.text.secondary,
  },
  inputContainer: {
    padding: 16,
    borderTopWidth: 1,
    borderTopColor: colors.border,
    backgroundColor: colors.background,
  },
  difficultyContainer: {
    marginBottom: 8,
    position: "relative",
  },
  difficultySelector: {
    flexDirection: "row",
    alignItems: "center",
  },
  difficultyDropdown: {
    position: "absolute",
    top: -100,
    left: 0,
    backgroundColor: colors.background,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: colors.border,
    padding: 8,
    shadowColor: colors.shadow,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  difficultyOption: {
    paddingVertical: 8,
    paddingHorizontal: 12,
  },
  difficultyOptionText: {
    fontSize: 14,
    fontWeight: "500",
  },
  inputRow: {
    flexDirection: "row",
    alignItems: "center",
  },
  input: {
    flex: 1,
    backgroundColor: colors.card,
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 8,
    fontSize: 16,
    color: colors.text.primary,
    maxHeight: 100,
  },
  generateButton: {
    marginLeft: 8,
  },
});